<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>书本列表</title>
	</head>
	<body>
		<div>
			<input type="text" name="search" placeholder="请输入书名" />
			<button type="button" id="btn_search">搜索</button>
			<button type="button" id="btn_add">添加</button>
			<button type="button" id="btn_delSelected">批量删除</button>
			<button type="button" id="btn_download">下载选中数据</button>
			<button type="button" id="btn_rowEdit" hidden>退出行编辑模式</button>
		</div>
		<table border="1">
			<thead>
				<th><input type="checkbox" name="cb_select_all" /></th>
				<th>id</th>
				<th>名称</th>
				<th>价格</th>
				<th>出版日期</th>
				<th>数量</th>
				<th>操作</th>
			</thead>
			<tbody>
				
			</tbody>
		</table>
		<script src="../../js/jquery-3.5.1.js" type="text/javascript" charset="utf-8"></script>
		<script type="text/javascript">
			let books = [
				{id: 1, name: 'Java从入门到放弃', price: 80, tdate: '2020-07-01', count: 1, account: "hehe"},
				{id: 2, name: 'Vue从入门到放弃', price: 90, tdate: '2020-07-02', count: 1, account: "haha"},
				{id: 3, name: 'Mysql从入门到放弃', price: 100.01, tdate: '2020-07-03', count: 1, account: "hehe"},
				{id: 4, name: '啥都从入门到放弃', price: 70.00, tdate: '2020-07-04', count: 1, account: "haha"},
			];
			
			let data = JSON.parse(localStorage.getItem("data"));
			if(!data) {
				data = books;
				localStorage.setItem("data", JSON.stringify(data));
			}
			
			//模拟登录成功
			sessionStorage.setItem("account", "hehe");
			let $tbody = $("table").find("tbody");
			
			/**
			 * init初始化函数
			 */
			function init() {
				//绑定事件
				$("#btn_search").click(search);
				$("#btn_add").click(toAdd);
				$("#btn_delSelected").click(delSelected);
				$("input[name='cb_select_all']").change(selectAll);
				$tbody.find("tr").dblclick(rowEdit);//双击事件
				$("#btn_rowEdit").click(save);
				$("#btn_download").click(download);
			}
			function download() {
				//选中数据
				let selectData = [];//保存选中的数据
				$("input[name='cb_select']:checked").each(function(index, item) {
					console.log(item.value);
					
					let id = $(item).val();
					
					for(let item of data) {
						if(item.id === parseInt(id)) {
							selectData.push(item);
						}
					}
				})
				//下载
				let a = document.createElement("a");
				let blob = new Blob([JSON.stringify(selectData)]);
				a.href = URL.createObjectURL(blob);
				a.download = "data.json";
				a.click();
			}
			let editTr = null;
			
			function save() {
				if(!editTr) {
					return;
				}
				let editData=null;
				let editIndex=0;
				let editDataId=editTr.find("input[name='cb_select']").val();
				console.log(editDataId);
				for (let index in data) {
					let item=data[index];
					if (item.id===parseInt(editDataId)) {
						editData=item;
						editIndex=index;
						break;
					}
				}
				editTr.children().each(function(index, item) {
					if (this.title!=="nodit") {
						
					//获取输入框
					let input=$(item).find("input");
					//获取input中value
					let value=input.val();
					//删除input 
					console.log(value);
					input.remove();
					//将value添加提交到td中
					$(item).text(value);
					if (typeof editData[this.title]==="number") {
						 if (value.indexOf(".") != -1) {
						 	editData[this.title]=parseFloat(value);
						 } else{
							editData[this.title]=parseInt(value);
						 }
					}else{
						editData[this.title]=value;
						console.log(editData[this.title]);
					}
					
					}
					
				});
					//实现数据保存到数组中
                     console.log(editData);
					 data.splice(editIndex,1,editData);
					 console.log(data.splice(editIndex,1,editData));
					//将数组更新到localStorage中
					localStorage.setItem("data", JSON.stringify(data));
					console.log(data);
				
			}
			
			function rowEdit() {
				
					
				$("#btn_rowEdit").show();
				
				editTr = $(this);
				//$(this)：表示的是tr
				$(this).children().each(function(index, item) {
					if(this.title !== "noedit"&&$(this).find("input").length === 0) {
						//将td中内容获取保存
						let td = $(this);
						//此时使用$(this)，表示td
						console.log( $(this).text());
						let text = $(this).text();
						//将td中的内容清空
						$(this).text("");
						console.log(text);
						//在td里面插入一个input
						// $(this).html("<input type='text'>");//不推荐
						let input = document.createElement("input");
						input.type = "text";
						input.value = text;
						let widthValue = 10 * text.length;
						input.style = "width: " + widthValue + "px";
						//添加到td中
						$(this).append(input);
						console.log($(this).append(input));
						//input绑定失去焦点事件
						// input.onblur = function() {
						// 	console.log("失去焦点");
						// 	//当input失去焦点时，将input中的内容保存到变量
						// 	// console.log(this);
						// 	let value = input.value;
						// 	//删除input标签
						// 	$(input).remove();
						// 	//将input的内容显示在td中
						// 	td.text(value);
						// }
					}
				});
			}
			
			function selectAll() {
				$("input[name='cb_select']").prop("checked", $(this).prop("checked"));
			}
			
			function delSelected() {
				//获取所有选中name为cb_select的checkbox
				$("input[name='cb_select']:checked").each(function(index, item) {
					// data.splice($(item).val(), 1);
					for(let i in data) {
						let dataItem = data[i];
						if(parseInt($(item).val()) === dataItem.id) {
							data.splice(i, 1)
						}
					}
				});
				$tbody.empty();
				update();
				localStorage.setItem("data", JSON.stringify(data));
			}
			
			function toEdit(index) {
				let item = data[index];
				sessionStorage.setItem("index", index);
				sessionStorage.setItem("item", JSON.stringify(item));
				location.href = "02-add.html";
			}
			
			function toAdd() {
				// sessionStorage.setItem("index", null);
				// sessionStorage.setItem("item", null);
				sessionStorage.removeItem("index");
				sessionStorage.removeItem("item");
				location.href = "02-add.html";
			}
			
			function del(index) {
				data.splice(index, 1);
				localStorage.setItem("data", JSON.stringify(data));
				$tbody.empty();
				update();
			}
			
			function search() {
				console.log("search");
				let search = $("input[name='search']").val();
				$tbody.empty();
				update(search);
			}
			
			function update(bookName) {
				console.log(data);
				//不需要使用break或continue等操作，可以使用$.each
				for(let index in data){
					let item = data[index];
					// console.log(item);
					//console.log(sessionStorage.getItem("loginAccount"))
					console.log(sessionStorage.getItem("account"),item.account);
					if(sessionStorage.getItem("account") !== item.account) {
						continue;
					}
					if(bookName && item.name.toLowerCase().indexOf(bookName.toLowerCase()) === -1) {
						continue;
					}
					console.log(1);
					let tr = `
						<tr>
							<td title="noedit"><input type="checkbox" name="cb_select" value="${item.id}" /></td>
							<td title="id">${item.id}</td>
							<td title="name">${item.name}</td>
							<td title="price">${item.price}</td>
							<td title="tdate">${item.tdate}</td>
							<td title="count">${item.count}</td>
							<td title="noedit">
								<button type="button" onclick="toEdit(${index})">编辑</button>
								<button type="button" onclick="del(${index})">删除</button>
							</td>
						</tr>
					`;
					$tbody.append(tr);
				}
			}
			
			update();
			init();
		</script>
	</body>
</html>
